import React, {Component, useContext, useEffect, useReducer, useState} from 'react';
import axios from "axios";
import '../02-advanced/filmpage.css'

//创建Context对象
//供应商给客户提供服务
//useContext减少组件层级
const GlobalContext = React.createContext()

const intialState = {
    info: '',
    list: [],
}

const reducer = (prevState, action) => {
    let newState = {...prevState}
    switch (action.type) {
        case 'change-list':
            newState.list = action.value
            return newState
        case 'change-item':
            newState.info = action.value
            return newState
        default:
            return false
    }
}
export default function App() {
    const [state, dispatch] = useReducer(reducer, intialState)

    useEffect(() => {
        axios.get(`test.json`).then(res => {
            dispatch({
                type: 'change-list',
                value: res.data.data.films
            })
        })
    }, [])

    return (
        <GlobalContext.Provider className="Provider" value={{//可写:方法,对象
            state,
            dispatch,
        }}>
            <div>
                {
                    state.list.map(item =>
                        <Filmitem key={item.filmId} {...item}></Filmitem>
                    )
                }

                <FilmDetail></FilmDetail>
            </div>
        </GlobalContext.Provider>
    )
}

//受控组件

function Filmitem(props) {
    let {name, poster, grade, synopsis} = props
    const {dispatch} = useContext(GlobalContext)
    return (
        <div className='filmitem' onClick={() => {
            dispatch({
                type: 'change-item',
                value: synopsis
            })
        }}>
            <img src={poster} alt={name}/>
            <h4>{name}</h4>
            <div>观众评分：{grade}</div>
        </div>
    )
}

function FilmDetail() {
    const {state} = useContext(GlobalContext)
    return (
        <div className='filmiDetail'>
            {state.info}
        </div>
    )

}




